﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;

namespace _180FrameWork.Common
{
    public class MyConfigHelper
    {
        //system.configuration.configuration a=configurationmanager.openexeconfiguration
        Configuration myconfig;
        public MyConfigHelper()
        {
            LoadConfig("myconfig.xml");
        }

        public MyConfigHelper(string filename)
        {
            LoadConfig(filename);
        }

        private void LoadConfig(string filename)
        {
            string filepath = "";
            //判断是否完整路径
            if (Path.IsPathRooted(filename))
            {
                filepath = filename;
            }
            else
            {
                filepath = System.AppDomain.CurrentDomain.BaseDirectory + @"\" + filename;
            }
         
            if (File.Exists(filepath))
            {
                ExeConfigurationFileMap map = new ExeConfigurationFileMap();
                map.ExeConfigFilename = filepath;
                myconfig = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            }
        }
        /// <summary>
        /// 获取字段值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetValue(string key)
        {
            try
            {
                if (myconfig != null)
                {
                    return myconfig.AppSettings.Settings[key].Value;
                }
                else
                {
                    return "";
                }
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 写入字段值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SetValue(string key, string value)
        {
            try
            {
                myconfig.AppSettings.Settings[key].Value = value;
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        public bool Save()
        {
            try
            {
                myconfig.Save();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
